'''
#Coding: utf-8
#Project: agro-traceability
#Author: rtf
#Time: 2020-08-17 11:26:31
#FileName: menu_button.py
#Softwar: PyCharm
'''


import json
from trump.utils import ok, fail
from utils.params_validate_decorator import validate_params
from trump.query import create_item, delete_item, get_items, get_item


@validate_params([["role_code", str, True], ["menus", list, True]])
async def post(app, request):
    params = request.json

    menus = params.get("menus")
    role_code = params.get("role_code")

    data = []
    for menu in menus:
        buttons = menu.get("buttons")
        data.append({"role_code": role_code,
                     "menu_code": menu.get("menu_code"),
                     "buttons": json.dumps(buttons, ensure_ascii=False)})
    result = await get_items(app.ctx.pool, "menu_button", {"role_code": role_code})
    if result:
        ids = ",".join(str(x.get("id")) for x in result)
        await delete_item(app.ctx.pool, "menu_button", ids)
    await create_item(app.ctx.pool, "menu_button", data)

    return ok(data="设置成功!", return_msg="设置成功!")


@validate_params([["menu_code", str, False], ["role_code", str, False]])
async def ls(app, request):
    params = request.args
    role_code = request.get("user").get("role_code")
    menu_code = params.get("menu_code")

    if not menu_code and not params.get("role_code"):
        return fail(data="缺少必传参数!", return_msg="缺少必传参数!")

    if params.get("role_code"):
        role_code = params.get("role_code")

        role_menu_button = await get_items(app.ctx.pool, "menu_button", {"role_code": role_code})
        for i in role_menu_button:
            i["buttons"] = i.get("buttons") if i.get("buttons") else dict()
        return ok(role_menu_button)

    role_menu_button = await get_items(app.ctx.pool, "menu_button", {"role_code": role_code, "menu_code": menu_code})

    buttons = {}
    data = []
    if role_menu_button:
        role_menu_button = role_menu_button[0]
        if role_menu_button.get("buttons"):
            buttons = json.loads(role_menu_button.get("buttons"))

    if buttons:
        menu = await get_item(app.ctx.pool, "manager_menu", menu_code, column="menu_code")
        menu_buttons = json.loads(menu.get("buttons")) if menu and menu.get("buttons") else list()

        for button in menu_buttons:
            if buttons.get(button.get("key")):
                data.append(button)

    return ok(data)